package cloud.pangui.core.mongo.operate;

import com.mongodb.MongoException;
import cloud.pangui.core.mongo.utils.SqlEleParseUtil;
import cloud.pangui.core.mongo.utils.SqlWhereParseUtils;


import static cloud.pangui.core.mongo.utils.SqlEleParseUtil.toInt;

/**
 * @Auther hepangui
 * @Date 2020/10/06 0001
*/
public class SqlUpdate extends Update {


	/**
	 * 构造一个sqlUpdate
	 * @param sql
	 */
	SqlUpdate(String sql) {
		this.build(sql);
	}

	public Update build(String sql) {
		String sqlCopy = sql.replaceAll("\n|\t|\r|\n\r", " ");
		String sqlUpper = sqlCopy.toUpperCase();

		int updateBegin = sqlUpper.indexOf("UPDATE ");
		int setBegin = sqlUpper.indexOf(" SET ");
		int whereBegin = sqlUpper.indexOf(" WHERE ");
		if (updateBegin == -1 || setBegin == -1) {
			throw new MongoException("sql语句有误，必须有update和set");
		}

		String tableStr = sqlCopy.substring(updateBegin + "UPDATE ".length(), setBegin);
		this.collectionName = tableStr.trim();

		String setStr = sqlCopy.substring(setBegin + " SET ".length(), whereBegin > -1 ? whereBegin : sqlCopy.length());
		parseSet(setStr);
		if (whereBegin != -1) {
			String whereSql = sqlCopy.substring(whereBegin + " WHERE ".length());
			this.where(SqlWhereParseUtils.parseWhere(whereSql,Where.SIMPLE_MODE));
		}
		return this;
	}


	/**
	 * 解析set
	 * set a= '666' , b='sdsd',c=7 ,d=d+1
	 * @param setStr
	 */
	private void parseSet(String setStr) {
		String[] split = setStr.split(",");
		for (String s : split) {
			boolean inStr = false;
			int i = 0;
			for (; i < s.length(); i++) {
				if (s.charAt(i) == '\'') {
					inStr = !inStr;
				}
				if (!inStr && s.charAt(i) == '=') {
					break;
				}
			}
			if (i < s.length()) {
				String key = s.substring(0, i).trim();
				String value = s.substring(i + 1).trim();
				// set a =a +1;
				if (value.indexOf("'") == -1 && value.indexOf("+") > -1) {
					int incr = toInt(value.substring(value.indexOf("+") + 1).trim());
					this.incr(key, incr);
				} else {
					this.set(key, SqlEleParseUtil.parseSimpleEle(value).toExpression());
				}
			}else{
				throw new MongoException("update 语句错误：" + s);
			}
		}
	}
}
